package servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

@WebFilter(filterName = "shoppingFilter" , value={"/shoppingcart.html","/Personal_homepage/Personal.html"})
public class shoppingFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession();
        System.out.println("============================="+session.getAttribute("user"));
        if (session.getAttribute("user") == null){
            // 说明未登录
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            // 获取应用上下文对象
            ServletContext servletContext = request.getServletContext();
            String contextPath = servletContext.getContextPath();
            String url = contextPath + "/login/" + URLEncoder.encode("Login-M","utf-8") + ".html";
            //跳转登录页
            httpServletResponse.sendRedirect(url);
            //保存当前页面地址
            String requestURI = httpServletRequest.getRequestURI();
            session.setAttribute("requesturl", requestURI);
            return;
            //不允许访问目标资源 过滤链
        }
        chain.doFilter(request, response);
    }


}
